﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ControlCenter.Model;
using ControlCenter.Model.BizEntities;
using ControlCenter.Model.WebApiDto;
using Dapper;

namespace ControlCenter.Data
{
    /// <summary>
    /// 心跳日志仓储类
    /// </summary>
    public class HeartLogRepository : RepositoryBase, IHeartLogRepository
    {
        /// <summary>
        /// 查询最近的心跳日志
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public async Task<IEnumerable<QueryNearLogDto>> QueryNearLogs(DateTime time)
        {
            string sql = @"SELECT TOP 1000 ObjectId,HeartType,MAX(Time) Time FROM (
                SELECT TOP 1000 * FROM HeartLog WHERE [Time]>=@Time ORDER BY Time DESC
                )Temp
                GROUP BY ObjectId, HeartType";
            return await ControlCenterDbConn.QueryAsync<QueryNearLogDto>(sql, new {Time=time});
        }

        /// <summary>
        /// 批量添加心跳日志
        /// </summary>
        /// <param name="heartLogs"></param>
        /// <returns></returns>
        public async Task<bool> BatchAddLogs(List<HeartLog> heartLogs)
        {
            if (heartLogs == null || heartLogs.Count == 0)
            {
                return true;
            }
            string sql = @"INSERT INTO [dbo].[HeartLog]
                   ([HeartType]
                   ,[Time]
                   ,[ObjectId])
             VALUES
                   (@HeartType
                   ,@Time
                   ,@ObjectId)";
            foreach (var log in heartLogs)
            {
                await ControlCenterDbConn.ExecuteAsync(sql, log);
            }
            return true;
        }
        
    }
}
